/*
 * @Description: 新建页基础信息相关
 */
/*global setMatchRequestToken*/
import {defineStore} from 'pinia';
import pinia from '@/store';
import {useTemplateStore} from './template';
import globalData, {AT_ALL} from '@/plugins/data';
import globalMethods, {urlParamsJson} from '@/plugins/methods';
import api from '@/api';
import emitter from '@/utils/emitter';

// 督办主题长度
const SUPERVISE_TITLE_LENTH = 85;

export const useBaseInfoStore = defineStore('baseInfo', {
  state: () => ({
    isHideGlobalLoading: true, //全局loading单独控制
    isBaseInfoReady: false, //数据是否准备好
    baseInfo: null, // 全量基础信息
    formInfo: {}, // 表单相关input、下拉框信息
    moreSetting: {}, // 更多设置
    lockParam: {}, //cap4加锁的信息
    attachments: { atts: [] }, // 附件
    relationDocs: { atts: [] }, // 关联文档
    businessData: null, //业务参数
    orderButtons: [], //协同顶部，标题下方的按钮：会议、附件、致信交流等
    relatedProject: {}, //关联项目
    postscript: '', //附言格式化之后的数据
    unCancelledVisor: null, // 不能取消的督办人
    defaultSubject: $.i18n('common.default.subject.value2'), // 默认标题
    appointedPerson: '', // 指定人员id值
    secretLevelAble: false, // 是否启用密级插件
    serverToLocalTime: 0, // 服务器时间和本地时间的差异
    $previewImg: null, // 图片预览dom值
    imgAtts: [], // 图片类型的附件数组
    pageData: [], // 更多设置页面数据
    print: {}, //打印数据，意见、附言
    pushPeopleList: [], // 推送人员
    isEdit: false, //处理页面用。是否是编辑态
    isDataReady: false, // 页面数据加载完毕
    processSelectItems: [], //工作流流程选人数据
    needCheckRule: true, //表单弱校验二次确认
    weekSubmit: false, //工作流选人确认
    hasAddNode: false, //是否进行了加签，保存待发会用到
    attachmentUploading: false, //附件上传中，任意附件未上传完毕都是true
    showDealArea: true, //显示处理区域 cap4多正文切换，非主表视图要隐藏
    attachmentLogs: [],
    otherParamData: { data: {} },
    pigeonholeId: '', //归档id，弱校验之后无需提示
    regexAsync: false, //正则弱校验确认后的结果
    canSign:false,//是否支持签章
    canEdit:false,//是否可以修改正文
    thirdPartyContext:{}//三方拓展的上下文数据
  }),
  actions: {
    /**
     * @description: 获取新建页面全量基本信息
     */
    async getBaseInfo(params) {
      const {
        templateId,
        from,
        projectId,
        summaryId,
        affairId,
        openFrom,
        baseObjectId,
        baseApp,
        method,
        isSummary,
        cashId,
        processId,
        designId,
        docId,
      } = globalData;
      this.isBaseInfoReady = false;
      let urlParams = urlParamsJson();
      this.baseInfo = await api.newCollGetBaseInfo({
        ...urlParams,
        ...params,
        templateId,
        from,
        projectId,
        summaryId,
        affairId,
        openFrom,
        method,
        baseObjectId,
        baseApp,
        cashId,
        processId,
        designId,
        docId,
      });
      const businessData = this.baseInfo.businessData;
      //如果url没有，就从这里设置
      if (!summaryId) {
        globalData.summaryId = businessData.summary.id;
      }
      //始终取接口返回后的id，相信后端计算，这个id关联人员、致信穿透等场景会重载修改
      globalData.affairId = businessData.affair.id;
      // 时间戳
      this.serverToLocalTime = +businessData.other.serverTimestamp - new Date().getTime();
      // 密级插件
      this.secretLevelAble = businessData.pluginInfo.includes('secretLevel');
      // 不能取消的督办人
      this.unCancelledVisor = businessData.superviseData?.unCancelledVisor;
      //标题下面的按钮
      this.orderButtons = this.baseInfo?.orderButtons?.orderButtons || [];
      // 附件
      //顶部的附件可以收藏
      if (this.baseInfo.attachments) {
        this.baseInfo.attachments.atts.forEach((att) => {
          att.canFavorite = true;
          if (att?.type == 0) {//接口不文明
            //设置是否需要克隆附件属性 新建时候的重复发起、模版需要
            att.needClone = this.baseInfo.attachments?.cloneOriginalAtts === true;
          }
        });
      }
      this.attachments = this.baseInfo.attachments = this.baseInfo.attachments || {
        atts: []
      };
      // 关联文档
      this.relationDocs = this.baseInfo.relationDocs = this.baseInfo.relationDocs || {
        atts: []
      };
      // 业务数据
      this.businessData = businessData || {};

      // 关联项目
      this.relatedProject = this.baseInfo.relatedProject || {};

      // 封装form基本信息对象
      this.formInfo = {
        subject: this.baseInfo.subject, // 标题
        importantLevel: this.baseInfo.importantLevel, // 重要程度
        workflowInfo: this.baseInfo.workflowInfo, // 流程信息
        prePigeonhole: this.baseInfo.prePigeonhole, // 预归档信息
        relatedProject: this.baseInfo.relatedProject, // 关联项目
        businessData //业务参数
      };
      const {workflowInfo} = this.formInfo;
      if (workflowInfo?.workflowNodesInfo && !workflowInfo.workflowNodesInfo?.value) {
        Vue.set(workflowInfo.workflowNodesInfo, 'value', ''); // 响应式
      }
      //cap4加锁信息
      this.lockParam = { ...businessData.formData };
      //附言格式化
      this.postscript = this.baseInfo.postscript?.contents?.map((d) => `${d}`).join('\n') || '';
      //根据返回值，设置iframe的src
      useTemplateStore().setZWIframeUrl(this.baseInfo.zwIframe);
      //是否是处理页面编辑态
      this.isEdit = businessData.other.hasDealArea;

      // 初始化流程期限。新建页面用
      if (this.baseInfo && !isSummary) {
        +this.baseInfo.workflowDeadLine.deadlines.value > 0 &&
          +this.baseInfo.workflowDeadLine.deadlines.value !== -1 &&
          (this.baseInfo.workflowDeadLine.deadLineDateTime.value = await this.getDateTimeValue({
            minutes: this.baseInfo.workflowDeadLine.deadlines.value,
            isCustomMinute: true
          }));
      }
      // matchRequestToken
      setMatchRequestToken(businessData.workflow.matchRequestToken);
      this.isBaseInfoReady = true;
      //select组件只有undefined才能显示placeholder
      if (this.baseInfo.secretLevel && !this.baseInfo.secretLevel.value) {
        Vue.set(this.baseInfo.secretLevel, 'value', undefined); // 响应式
      }
      const { currentUser } = businessData;
      //挂载全局用户
      $.ctx.CurrentUser = currentUser;
      //设置是否支持签章
      const {nodePolicy} =businessData;
      if (nodePolicy){
        let actionList = [...(nodePolicy.advanceActionList || []), ...(nodePolicy.commonActionList || [])];
        this.canSign=actionList.includes('Sign');
        this.canEdit=actionList.includes('Edit');
        nodePolicy.canSign=this.canSign;
        nodePolicy.canEdit=this.canEdit;
      }
      return this.baseInfo;
    },

    setDataReady() {
      this.isDataReady = true;
    },

    /**
     * @description: 更新主数据
     */
    setColMainData(data) {
      this.baseInfo.collaborationSubmitData.colMainData = Object.assign(
        this.baseInfo.collaborationSubmitData.colMainData,
        data
      );
    },
    /**
     * 设置正文类型
     * @param bodyType
     */
    setContentType(bodyType) {
      this.setColMainData({bodyType});
      this.baseInfo.contentType.value = bodyType;
      this.baseInfo.businessData.summary.bodyType = bodyType;
    },

    /**
     * @description: 关联项目
     */
    setRelatedProject(projectId) {
      this.relatedProject.projectId = projectId;
    },

    /**
     * @description: 跟踪事项
     */
    setTrackData(trackSet) {
      this.baseInfo.businessData.trackData = trackSet;
    },

    /**
     * @description: 预归档
     */
    setPrePigeonhole(id) {
      this.baseInfo.prePigeonhole.value = id;
      // 更新主数据id值
      this.setColMainData({
        archiveId: id, // 归档目录id
        prevArchiveId: id // 预归档目录id
      });
    },

    /**
     * @description: 图片预览组件dom
     */
    setPreviewImgRef(dom) {
      this.$previewImg = dom;
    },

    /**
     * @description: 图片类型附件汇总（只加入可操作的）
     */
    setImgAtts(file) {
      if (this.imgAtts.some((item) => item.fileUrl === file.fileUrl)) return;
      this.imgAtts.push(file);
    },

    /**
     * @description: 获取更多设置页面数据
     */
    getPageData() {
      var _this = this;
      var defaultObj = {
        // 默认结构
        tracks: {},
        allowOperation: {},
        mergePolicyCheckbox: {},
        mergeAttitude: {},
        mergeContent: {},
        supervise: {},
        workflowDeadLine: {}
      };
      this.pageData = JSON.parse(
        JSON.stringify(
          this.baseInfo
            ? Object.assign(defaultObj, {
                tracks: _this.baseInfo.tracks, // 跟踪
                allowOperation: _this.baseInfo.allowOperation, // 允许操作
                mergePolicyCheckbox: {
                  // 合并处理策略
                  canStartMerge: _this.baseInfo.mergePolicy.canStartMerge,
                  canPreDealMerge: _this.baseInfo.mergePolicy.canPreDealMerge,
                  canAnyDealMerge: _this.baseInfo.mergePolicy.canAnyDealMerge,
                  mergeIgnoreCommentRequired: _this.baseInfo.mergePolicy.mergeIgnoreCommentRequired
                },
                mergeAttitude: _this.baseInfo.mergePolicy.mergeAttitude, // 态度
                mergeContent: _this.baseInfo.mergePolicy.mergeContent, // 意见
                supervise: { supervisorIds: '', supervisorNames: '', ..._this.baseInfo.supervise },
                workflowDeadLine: _this.baseInfo.workflowDeadLine
              })
            : defaultObj
        )
      );

      // 构造页面数据
      return this.pageData;
    },

    /**
     * @description: 保存更多设置的修改
     */
    saveEdit(obj) {
      console.log('save', obj);

      // 更新allowOperation
      Object.keys(this.baseInfo.allowOperation).forEach((key) => {
        // if (item.hidden) return;
        this.baseInfo.allowOperation[key].checked =
          obj.allowOperationCheckedList.indexOf(key) !== -1;
      });
      // 更新allowOperation
      Object.keys(this.baseInfo.mergePolicy).forEach((key) => {
        if (key === 'mergeAttitude' || key === 'mergeContent') return;
        this.baseInfo.mergePolicy[key].checked = obj.mergePolicyCheckedList.indexOf(key) !== -1;
      });

      // 更新剩余数据  //这个操作会导致抽取出来的独立属性断卡关联
      Object.assign(this.baseInfo, {
        tracks: obj.tracks, // 跟踪
        mergePolicy: {
          ...obj.mergePolicyCheckbox,
          mergeAttitude: obj.mergeAttitude, // 态度
          mergeContent: obj.mergeContent // 意见
        },
        supervise: obj.supervise, // 督办信息
        workflowDeadLine: obj.workflowDeadLine // 流程
      });
    },

    /**
     * @description: 获取指定分钟数后的日期
     * @param {String}minutes 单位分钟
     */
    async getDateTimeValue({ minutes, isCustomMinute }, params = {}) {
      // 参数表示在当前日期下要增加的天数
      if (isCustomMinute && parseInt(minutes) > 0) {
        return await api.calculateDateTime(minutes, params);
      }
      var now = new Date();
      if (minutes) {
        switch (minutes) {
          case '5':
          case '10':
          case '15':
          case '30':
          case '60':
          case '120':
          case '180':
          case '240':
          case '300':
          case '360':
          case '420':
          case '480':
          case '720':
          case '1440':
          case '2880':
          case '4320':
          case '5760':
          case '7200':
          case '8640':
          case '10080':
          case '14400':
          case '20160':
          case '21600':
          case '30240':
          case '43200':
          case '86400':
          case '129600':
            return await api.calculateDateTime(minutes, params);
          default:
            // return new Date(now).format("yyyy-MM-dd HH:mm");
            return now.getTime();
        }
      }
    },

    /**
     * @description: 保存前校验
     */
    async checkBeforeSave() {
      if (this.validateTrack() && this.validateSupervisor() && (await this.compareTime())) {
        return Promise.resolve();
      }
      return Promise.reject();
    },

    /**
     * @description: 校验标题：如果标题 为空|为默认值，提醒用户
     */
    validateSubject() {
      var subject = this.formInfo.subject.value;
      if (!subject || this.defaultSubject == subject) {
        // 提示标题不能为空
        Warning($.i18n('collaboration.common.titleNotNull'));
        return false;
      }

      return true;
    },

    /**
     * @description: 校验附件是否上传完毕，上传中不能进行提交
     */
    validateAttachmentUploading() {
      let attachmentUploading = this.attachmentUploading;
      if (attachmentUploading) {
        // 提示稍后操作  与产品确认提示文字:附件正在上传中，请稍后操作
        Warning($.i18n('collaboration.attachment.uploading.hook'));
        return false;
      }

      return true;
    },

    /**
     * @description: 校验指定跟踪人：如果选择了指定跟踪人员但是又没有选择具体人员的话
     */
    validateTrack() {
      var isChecked = this.pageData.tracks.type === '2'; // 选定“指定人员”

      if (isChecked && this.appointedPerson == '') {
        // 指定跟踪人不能为空，请选择指定跟踪人！
        globalMethods.message.error($.i18n('collaboration.newColl.alert.zdgzrNotNull'));
        return false;
      }
      return true;
    },

    /**
     * 提交和暂存待办使用
     * @description: 校验指定跟踪人：如果选择了指定跟踪人员但是又没有选择具体人员的话
     */
    validateTrackDeal() {
      let trackData = this.baseInfo.businessData.trackData;
      console.log('trackData:', trackData);
      if (trackData == null) {
        return true;
      }
      let isChecked = trackData.isTrack && !trackData.isTrackAll;
      if (isChecked && (trackData.trackMembers == null || trackData.trackMembers === '')) {
        // 指定跟踪人不能为空，请选择指定跟踪人！
        globalMethods.message.error($.i18n('collaboration.newColl.alert.zdgzrNotNull'));
        return false;
      }
      return true;
    },

    /**
     * @description: 验证督办设置：var isV5Member = ${CurrentUser.externalType == 0}; isV5Member为true才校验
     */
    validateSupervisor() {
      var supervisorIds = this.pageData.supervise.supervisorIds; // 逗号分隔id
      var unCancelledVisor = this.unCancelledVisor; // 不能取消的督办人
      var superviseTitle = this.pageData.supervise.superviseTitle;
      var superviseAwakeDate = this.pageData.supervise.superviseAwakeDate; // 督办期限
      var rule = /^[^\\|\\"'<>]*$/;

      // 督办主题包含特殊字符(\|\"<>')请重新录入!
      if (!rule.test(superviseTitle)) {
        globalMethods.message.error(
          $.i18n('collaboration.common.common.supervise.specialCharacters')
        ); // i18n('collaboration.common.common.supervise.specialCharacters')
        return false;
      }

      // 督办人员校验
      if (supervisorIds) {
        var sArray = supervisorIds.split(',');
        var ids = new Array();
        sArray.forEach((i) => {
          i && i.trim() && ids.push(i);
        });

        // 最多只允许50个人督办,请重新选择督办人!
        if (ids.length > 50) {
          globalMethods.message.error($.i18n('collaboration.newColl.alert.select10Supervision'));
          return false;
        }

        // 设置了督办人员，就必须设置督办时间
        if (!superviseAwakeDate) {
          // 请选择督办期限
          globalMethods.message.error(
            $.i18n('collaboration.newColl.alert.selectSupervisionPeriod')
          );
          return false;
        }

        // 模板自带督办人员是否被删除检测
        if (unCancelledVisor) {
          var uArray = unCancelledVisor.split(',');
          uArray.forEach((u) => {
            if (supervisorIds.search(u) === -1) {
              // 未找到对应id值
              // 模板自带督办人员不允许删除!
              globalMethods.message.error(
                $.i18n('collaboration.newCollaboration.templatePersonnelNoDel')
              );
              return false;
            }
          });
        }
      } else if (unCancelledVisor) {
        // 模板自带督办人员不允许删除!
        globalMethods.message.error(
          $.i18n('collaboration.newCollaboration.templatePersonnelNoDel')
        );
        return false;
      }

      // 督办主题长度不能超过85字
      if (superviseTitle && superviseTitle.length > SUPERVISE_TITLE_LENTH) {
        globalMethods.message.error($.i18n('collaboration.newColl.alert.supervisionLong85'));
        return false;
      }

      // 设置了督办主题或者督办时间，但没有设置督办人，给出提示
      if ((superviseAwakeDate || superviseTitle) && !supervisorIds) {
        // 请选择督办人员!
        globalMethods.message.error($.i18n('collaboration.newColl.alert.selectSupervision'));
        return false;
      }
      return true;
    },

    /**
     * @description: 校验密级是否为空
     */
    checkSecret() {
      var fileSecretLevel = this.baseInfo.secretLevel.value; // 密级选中值
      // secretLevelAble是全局变量, 含义为是否开启密级插件
      if (this.secretLevelAble === 'true' || this.secretLevelAble === true) {
        // 密级是否开启
        if (!fileSecretLevel) {
          Warning($.i18n('common.secret.null.alert'));
          return false;
        }
      }
      return true;
    },

    /**
     * @description: 超期提醒与提前提醒时间设置的比较
     */
    async compareTime() {
      var advanceRemindTime = +this.pageData.workflowDeadLine.advanceRemind.value; // 提前提醒
      var deadLineTime = +this.pageData.workflowDeadLine.deadlines.value; // 流程期限
      var deadLineDateTime = this.pageData.workflowDeadLine.deadLineDateTime.value; // 自定义流程期限时间

      if (deadLineTime <= advanceRemindTime && !(!advanceRemindTime && !deadLineTime)) {
        if (deadLineDateTime) {
          // 流程期限小于、等于提前提醒时间
          var data = await this.getDateTimeValue({ minutes: advanceRemindTime });
          if (advanceRemindTime && data >= deadLineDateTime.valueOf()) {
            Warning($.i18n('collaboration.newColl.alert.lcqx'));
            return false;
          }
        } else {
          // 没有设置流程期限
          Warning($.i18n('collaboration.newColl.alert.lcqx'));
          // 重置为无
          this.baseInfo.workflowDeadLine.advanceRemind.value = '0';
          return false;
        }
      }

      return true;
    },

    /**
     * @description: 验证流程期限是小于当前系统时间
     */
    sendCheckDeadlineDatetime() {
      let deadLineDateTime = +this.baseInfo.workflowDeadLine.deadLineDateTime.value; // 自定义流程期限时间戳
      let deadLineTime = +this.pageData.workflowDeadLine.deadlines.value; // 流程期限
      let nowDateTime = new Date();
      if (deadLineTime) {
        if (deadLineDateTime && nowDateTime.getTime() + this.serverToLocalTime > deadLineDateTime) {
          Warning($.i18n('collaboration.newcoll.processTimeEarlier'));
          return true;
        }
      }
      return false;
    },

    async validateSupervise(resolve) {
      let supervisorIds = this.baseInfo?.supervise?.supervisorIds;
      if (supervisorIds && this.secretLevelAble) {
        let secretLevelValue = this.baseInfo.secretLevel?.value;
        let result = await api.commonCheckUserSecret(`${secretLevelValue},[${supervisorIds}]`);
        if (result) {
          let some = Object.values(result).some((value) => value === false);
          if (some) {
            globalMethods.confirm({
              title: globalMethods.i18n('common.system.hint.label'),
              // eslint-disable-next-line no-unused-vars
              content: (h) => (
                <div>
                  {/*国际化里面的<br>会被转义，用jsx语法处理*/}
                  {globalMethods
                    .i18n('collaboration.secretLevel.supervise.check')
                    .split('<br>')
                    .map((item) => (
                      <p>{item}</p>
                    ))}
                </div>
              ),
              onOk() {
                resolve(true);
              },
              onCancel() {
                resolve(false);
              }
            });
            return;
          }
        }
      }
      resolve(true);
    },
    /**
     * @description: 检查流程是否为空（CAP4模板不用校验流程是否为空）
     */
    validateProcess(warn = true) {
      if (globalData.isCap4) {
        return true;
      } else {
        let workflowParamData = window.workflowModule.getWorkflowParams();
        const { context } = workflowParamData;
        //processTemplateId 不为空或者-1 都说明是有流程的
        if (
          !context.processXml &&
          !context.processId &&
          (!context.processTemplateId || context.processTemplateId === '-1') &&
          globalData.isStandard
        ) {
          let result = this.processSelectItems && this.processSelectItems.length > 0;
          if (!result && warn) {
            globalMethods.warning({
              title: globalMethods.i18n('common.system.hint.label'),
              //流程不能为空
              content: globalMethods.i18n('collaboration.forward.workFlowNotNull'),
              onOk:()=>{ emitter.publish('newCol_selectPeopleOnclick')}
            });
          }
          return result;
        }
      }
      return true;
    },
    /**
     * @description: 设置全局loading
     * @param {Boolean}data 是否隐藏
     * @return {*}
     */
    setIsHideGlobalLoading(data = true) {
      this.isHideGlobalLoading = data;
    },
    /**
     * @description: 推送人员
     */
    updatePushPeopleList(newList) {
      //如果没传列表。说明就是改变了当前流程人员（目前已知：当前会签）需要更新列表
      if (!newList) {
        //获取当前流程改变的人员列表
        let { nodes } = JSON.parse($('#processChangeMessage').val());
        nodes = nodes.filter((item) => item.fromType == '3' && item.eleType == 'user');
        //过滤
        if (!nodes.length) return;

        //待添加数组
        const addList = [];
        const { pushPeopleList } = this;
        nodes.forEach((d) => {
          //如果当前列表没有就添加进去
          if (!pushPeopleList.some((dd) => dd.memberId === d.eleId)) {
            addList.push({
              memberName: d.eleName,
              memberId: d.eleId,
              affairId: globalData.affairId
            });
          }
        });
        if (!addList.length) return;
        //设置
        this.pushPeopleList = pushPeopleList.concat(addList);
        console.log('this.pushPeopleList', this.pushPeopleList);
      } else {
        //否则就是接口获取
        this.pushPeopleList = AT_ALL.concat(newList);
      }
      return this.pushPeopleList;
    },
    updateProcessSelectItems(itemList = []) {
      this.processSelectItems = itemList;
      return this.processSelectItems;
    },
    //修改附件
    updateAttachments(atts) {
      Object.assign(this.attachments, {
        atts
      });
      // this.attachments.atts=atts;
      console.log('修改了附件', this.attachments);
    },
    //修改关联文档
    updateRelationDocs(atts) {
      Object.assign(this.relationDocs, {
        atts
      });
      console.log('修改了关联文档', this.relationDocs);
      // this.relationDocs.atts=atts;
    },
    /**
     * 切换处理意见的显示状态
     * @param val
     */
    toggleDealArea(val) {
      this.showDealArea = val;
      console.log('toggleDealArea show/hidden', val);
    },
    /**
     * 修改工作流当前节点信息，新建后流程选人
     * @param workFlowNodesInfo
     */
    updateWorkflowNodesInfo(workFlowNodesInfo) {
      this.formInfo.workflowInfo.workflowNodesInfo.value = workFlowNodesInfo;
      console.log('updateWorkflowNodesInfo', this.formInfo.workflowInfo.workflowNodesInfo);
    },
  }
});
/**
 * @description: 警告弹窗
 */
function Warning(content) {
  globalMethods.warning({
    title: globalMethods.i18n('common.system.hint.label'),
    content: content
  });
}

export function useBaseInfoWithOut() {
  return useBaseInfoStore(pinia);
}

/**
 * 获取密级，内部使用
 * @returns {*|string}
 */
export function getAccessFileSecretLevel() {
  let baseInfoWithOut = useBaseInfoWithOut();
  if (!baseInfoWithOut.secretLevelAble) {
    return '';
  }
  return baseInfoWithOut.baseInfo?.secretLevel?.value || '';
}

/**
 * 挂载全局方法，兼容以前，给工作流提供获取密级的方法，兼容表单以及工作流
 */
window.getAccessFileSecretLevel = getAccessFileSecretLevel;
